#!/usr/bin/env bash
# Copyright (c) 2024 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0

CUR_DIR=$(pwd)
WORK_DIR="$CUR_DIR/oe_rpmver_workspace"
YUM_DIR="$WORK_DIR/yum"
YUM_CONFIG_FILE="$YUM_DIR/yum.conf"

REPOS=""

usage() {
printf "get rpm version based on dnf repository

usage:
    bash oe_rpmver.sh [-h] [-s REPOSITORY [-s ...]]

optional arguments:
    -s REPOSITORY  dnf repository address link (can be specified multiple times)
    -h             show the help message and exit
\n"
}

log_error() {
    echo "ERROR: $1"
}

parse_cmdline() {
    if [ $# -eq 0 ]; then
        usage; exit 0
    fi

    # parse cmd line arguments
    while getopts ":s:h" opt; do
        case "$opt" in
            s)
                if [ -z "$REPOS" ]; then
                    REPOS="$OPTARG"
                else
                    REPOS="$REPOS $OPTARG"
                fi
            ;;
            h)
                usage; exit 0
            ;;
            ?)
                echo "please check the params."; usage; return 1
            ;;
        esac
    done
    if [[ -z "$REPOS" ]]; then
        echo "invalid REPOSITORY arguments"; return 1
    fi
    return 0
}

check_requires() {
    local ret=0

    for c in repoquery; do
        command -v $c >/dev/null
        if [ $? -ne 0 ]; then
            echo "command $c not found"
            ret=1
        fi
    done

    return $ret
}

clean() {
    cd "$CUR_DIR" || :
    [[ -d "${WORK_DIR}" ]] && rm -rf "${WORK_DIR}"
}

create_yum_repo() {
    local yum_dir="$YUM_DIR"
    local yum_config_file="$YUM_CONFIG_FILE"
    local yum_repo_dir="${yum_dir}/yum.repos.d"
    local yum_repo_file="${yum_repo_dir}/os.repo"

    mkdir -p "$yum_repo_dir"

    cat > "${yum_config_file}" <<EOF
[main]
gpgcheck=1
installonly_limit=3
clean_requirements_on_remove=True
best=True
skip_if_unavailable=False
reposdir=${yum_repo_dir}
EOF

    local i=1
    for repo in $REPOS; do
        cat >> "${yum_repo_file}" <<EOF
[repo_$i]
name=repo_$i
baseurl=$repo
enabled=1
gpgcheck=0

EOF
        ((i++))
    done
}

do_main() {
    clean

    mkdir -p "$YUM_DIR"

    create_yum_repo

    local pkgs=$(repoquery -c "$YUM_CONFIG_FILE" -q --qf="%{name},%{version},%{version}-%{release}" --all --latest-limit=1)

    echo "package,version,fullver"
    echo "$pkgs"

    clean

    return 0
}

main() {
    parse_cmdline "$@"
    if [ $? -ne 0 ]; then
        log_error "parse params failed, try -h for help"
        return 1
    fi

    check_requires
    if [ $? -ne 0 ]; then
        log_error "check requires failed"
        return 1
    fi

    do_main
    if [ $? -ne 0 ]; then
        return 1
    fi

    return 0
}

main "$@"
